<template>
  <view class="container">
    <view class="smart-form">
      <uni-forms ref="formRef" :label-width="100" :modelValue="form" label-position="left" :rules="rules">
        <view class="smart-form-group">
          <view class="smart-form-group-content">
            <uni-forms-item class="smart-form-item" label="企业名称：" name="enterpriseName" required>
              <uni-easyinput type="input" trim="all" v-model="form.enterpriseName" placeholder="请输入企业名称" />
            </uni-forms-item>
            <uni-forms-item class="smart-form-item" label="预约电话：" name="reservationPhone" required>
              <uni-easyinput type="input" trim="all" v-model="form.reservationPhone" placeholder="请输入预约电话" />
            </uni-forms-item>
          </view>
        </view>
      </uni-forms>
      <view class="smart-form-submit fixed-bottom-button">
        <button class="smart-form-submit-btn" type="primary" @click="submit">查询</button>
      </view>
      <uni-section title="预约记录" type="line">
        <view class="reservation-list">
          <view class="item" v-for="item in reservationList" :key="item.reservationId">
            <view class="item-header">
              <view class="header-title-wrapper">
                <view class="header-title">{{ item.enterpriseName }}</view>
              </view>
            </view>
            <view class="content">
              <view class="status-tag" :class="getStatusClass(item.reservationState)">
                {{ getDictLabel(reservationStateList, item.reservationState) }}
              </view>
              <view class="info-row">
                <text class="label">预约类型：</text>
                <text class="value">{{ getDictLabel(reservationTypeList, item.reservationType) }}</text>
              </view>
              <view class="info-row">
                <text class="label">预约人：</text>
                <text class="value">{{ item.reservationUser }}</text>
              </view>
              <view class="info-row">
                <text class="label">联系电话：</text>
                <text class="value">{{ item.reservationPhone }}</text>
              </view>
              <view class="info-row">
                <text class="label">预约时间：</text>
                <text class="value">{{ item.reservationTime }}</text>
              </view>
              <view class="info-row">
                <text class="label">创建时间：</text>
                <text class="value">{{ item.createTime }}</text>
              </view>
            </view>
            <view class="footer">
              <view class="footer-button">
                <!-- 等待确认状态显示取消预约按钮 -->
                <button
                  v-if="getDictLabel(reservationStateList, item.reservationState) === '等待确认'"
                  class="cancel-reservation-btn"
                  @click="cancelReservation(item.reservationId)"
                >
                  取消预约
                </button>
                <!-- 预约成功状态显示展码核销按钮 -->
                <button
                  v-if="getDictLabel(reservationStateList, item.reservationState) === '预约成功'"
                  class="show-code-btn"
                  @click="showVerificationCode(item)"
                >
                  展码核销
                </button>
              </view>
            </view>
          </view>
        </view>
      </uni-section>
    </view>

    <!-- 二维码弹窗 -->
    <view class="qr-modal" v-if="showQRCodeModal">
      <view class="qr-modal-content">
        <view class="qr-modal-header">
          <text class="qr-modal-title">预约核销码</text>
          <text class="qr-modal-close" @click="closeQRCodeModal">×</text>
        </view>
        <view class="qr-code-wrapper">
          <!-- 使用 image 显示生成的二维码 -->
          <image
            v-if="qrCodeImage"
            class="qr-image"
            :src="qrCodeImage"
            mode="aspectFit"
            style="width: 200px; height: 200px;"
          ></image>
          <!-- 加载中提示 -->
          <view v-else class="loading-text">二维码生成中...</view>
        </view>
        <view class="qr-info">
          <view class="qr-info-item">
            <text class="qr-info-label">企业名称：</text>
            <text class="qr-info-value">{{ currentReservation.enterpriseName }}</text>
          </view>
          <view class="qr-info-item">
            <text class="qr-info-label">预约码：</text>
            <text class="qr-info-value qr-code-text">{{ currentReservation.reservationCode }}</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
  import { reactive, ref } from 'vue';
  import { reservationApi } from '@/api/business/oa/reservation-api';
  import { smartSentry } from '@/lib/smart-sentry';
  import { SmartLoading, SmartToast } from '@/lib/smart-support';
  import { dictApi } from "@/api/support/dict-api";
  import QRCode from 'qrcode';

  // 数据定义
  const reservationList = ref([])
  const reservationTypeList = ref([])
  const reservationStateList = ref([])

  // 二维码相关
  const showQRCodeModal = ref(false)
  const currentReservation = ref({})
  const qrCodeImage = ref('')

  // 表单相关
  const defaultFormData = {
    enterpriseName: '',
    reservationPhone: '',
  };
  const form = reactive({ ...defaultFormData });
  const formRef = ref();

  // 表单验证规则
  const rules = {
    enterpriseName: {
      rules: [{ required: true, errorMessage: '请输入公司名称' }],
    },
    reservationPhone: {
      rules: [{ required: true, errorMessage: '请输入预约人电话' }],
    },
  };

  // 生命周期钩子
  // 初始化时加载字典数据
  queryReservationTypeDict();
  queryReservationStateDict();

  // 方法定义
  // 查询预约类型字典数据
  async function queryReservationTypeDict() {
    try {
      const res = await dictApi.getDictDataListByCode("SUPPLIER_TYPE");
      reservationTypeList.value = res.data.map((e) => ({
        label: e.dataLabel,
        value: e.dataValue
      }));
    } catch (error) {
      smartSentry.captureError(error);
    }
  }

  // 查询预约状态字典数据
  async function queryReservationStateDict() {
    try {
      const res = await dictApi.getDictDataListByCode("RESERVATION_STATE");
      reservationStateList.value = res.data.map((e) => ({
        label: e.dataLabel,
        value: e.dataValue
      }));
    } catch (error) {
      smartSentry.captureError(error);
    }
  }

  // 获取字典标签
  function getDictLabel(dictList, value) {
    const dict = dictList.find(item => item.value === value);
    return dict ? dict.label : value;
  }

  // 表单提交
  async function submit() {
    try {
      await formRef.value.validate();
      SmartLoading.show();

      const res = await reservationApi.queryPage4public(form);
      reservationList.value = res.data;
    } catch (error) {
      if (error.errMsg) {
        console.log('表单验证错误:', error);
      } else {
        smartSentry.captureError(error);
      }
    } finally {
      SmartLoading.hide();
    }
  }

  // 取消预约
  function cancelReservation(reservationId) {
    console.log('取消预约，ID:', reservationId);
    SmartToast.success('取消预约功能待实现');
  }

  // 展码核销
  function showVerificationCode(reservation) {
    currentReservation.value = reservation;
    showQRCodeModal.value = true;
    qrCodeImage.value = ''; // 重置二维码图片
    // 生成二维码
    generateQRCode(reservation.reservationCode);
  }

  // 生成二维码
  async function generateQRCode(code) {
    try {
      // 使用 qrcode 库生成二维码
      const qrDataUrl = await QRCode.toDataURL(code, {
        width: 200,
        margin: 2,
        color: {
          dark: '#000000',
          light: '#ffffff'
        }
      });
      qrCodeImage.value = qrDataUrl;
    } catch (err) {
      console.error('生成二维码失败:', err);
      qrCodeImage.value = '';
      SmartToast.error('二维码生成失败');
    }
  }

  // 关闭二维码弹窗
  function closeQRCodeModal() {
    showQRCodeModal.value = false;
    qrCodeImage.value = '';
  }

  // 根据预约状态返回对应的样式类
  function getStatusClass(state) {
    const stateLabel = getDictLabel(reservationStateList.value, state);

    const statusClassMap = {
      '等待确认': 'waiting',
      '预约成功': 'success',
      '预约过期': 'expired',
      '预约取消': 'cancelled',
      '预约核销': 'verified'
    };

    return statusClassMap[stateLabel] || 'default';
  }
</script>

<style lang="scss" scoped>
@import '@/theme/reservation-list.scss';
</style>
